<template>
  <div>
    <slot></slot>
  </div>
</template>
<script>
import domtoimage from 'dom-to-image'

export default {
  props: {
    domId: String,
    title: String,
  },
  components: {},
  data() {
    return {
      dataUrl: '',
    }
  },
  mounted() {},
  methods: {
    // domtoimage生成base64图片
    downloadImage() {
      // 下载图片
      let node = document.getElementById(this.domId)
      let that = this
      domtoimage
        .toPng(node)
        .then(function (dataUrl) {
          that.dataUrl = dataUrl
          that.downloadFileByBase64(that.dataUrl, that.title)
          that.$emit('done')
          that.$message({
            message: '生成成功！',
            type: 'success',
          })
        })
        .catch(function (error) {
          console.error('生成失败', error)
          that.$emit('done')
          that.$message({
            message: '生成失败！',
            type: 'fail',
          })
        })
    },
    createImage(index, type) {
      let node = document.getElementById(this.domId)
      let that = this
      domtoimage
        .toPng(node)
        .then(function (dataUrl) {
          that.dataUrl = dataUrl
          if (type === 'blob') {
            that.$emit('createImageDone', { url: that.base64toBlob(dataUrl) })
          } else if (type === 'file') {
            that.$emit('createImageDone', { url: that.base64toFile(dataUrl) })
          } else {
            that.$emit('createImageDone', { url: dataUrl, index })
          }
        })
        .catch(function (error) {
          console.error('生成失败', error)
          that.$emit('done')
        })
    },
    base64toBlob(base64) {
      var arr = base64.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    base64toFile(base64) {
      const blob = this.base64toBlob(base64)
      const file = new File([blob], 'poster.png', { type: blob.type })
      return file
    },
    downloadFile(url, name) {
      var a = document.createElement('a') //新建一个a链接
      a.setAttribute('href', url) // a链接的url为图片的url
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      let clickEvent = document.createEvent('MouseEvents')
      clickEvent.initEvent('click', true, true)
      a.dispatchEvent(clickEvent)
    },
    downloadFileByBase64(base64, name) {
      var myBlob = this.base64toBlob(base64)
      var myUrl = URL.createObjectURL(myBlob) //创建图片的临时url
      this.downloadFile(myUrl, name)
    },
  },
}
</script>
